package app.base.common;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

public class FilterServlet extends HttpServlet implements Filter {   

	private static final long serialVersionUID = 1L;
	
	private FilterConfig filterConfig;   
	private String[] freePages;   
	private String loginPage = null;   	  
	 
	/**  
	  * 初始化filter（这里重写父类的方法）  
	  * @param filterConfig FilterConfig filter配置对象  
	  * @throws ServletException  
	*/  
	public void init(FilterConfig filterConfig) throws ServletException {   
		this.filterConfig = filterConfig;
		this.loginPage = filterConfig.getInitParameter("LoginPage");   
		String pages = filterConfig.getInitParameter("FreePages");
		  
		if(this.loginPage == null || pages == null || loginPage.trim().length() == 0 || pages.trim().length() == 0) {   
			throw new ServletException("web.xml中filterServlet没有配置初始化参数   \"LoginPage\"或\"FreePages\".");   
		}   
		  
		int index = 0;
		StringTokenizer strTokenizer = new StringTokenizer(pages, ";");   
		this.freePages = new String[strTokenizer.countTokens()]; 
		while(strTokenizer.hasMoreTokens()) {   
			this.freePages[index++] = strTokenizer.nextToken();   
		}   
		  
		if(!isFreePage(this.loginPage)) {    
			throw new ServletException("web.xml中filter初始化参数\"LoginPage\"的值 必须是\"FreePages\"中的某个页面.");   
		}
	 }   
	  
	/**  
	  * 判断一个请求URI是否是不过滤的页面  
	  * @param requestURI String 请求URI  
	  * @return boolean 返回true为不过滤页面  
	*/  
	private boolean isFreePage(String requestURI) {   
		for(int i = 0; i < this.freePages.length; i++) {   
			if(requestURI.endsWith(this.freePages[i])) {   
				return true;   
			}   
		}
		return false;   
	}   
	  
	 /**  
	  * 判断请求是否为有效Session  
	  * @param request ServletRequest 请求对象  
	  * @return boolean 返回true为有效Session  
	  */  
	private boolean isValidSession(ServletRequest request) {   
		HttpServletRequest httpRequest = (HttpServletRequest)request; 
		
		if(!(httpRequest.getSession().getAttribute(Utility.LOGIN_USER_SESSION_INFO) == null)) {   
			return true;   
		}   
	
		return false;   
	}   
	  
	 /**  
	  * 过滤动作  
	  * @param request ServletRequest 请求对象  
	  * @param response ServletResponse 响应对象  
	  * @param filterChain FilterChain 过滤器链对象  
	  */  
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {   
		HttpServletRequest httpRequest = (HttpServletRequest)request;   
		HttpServletResponse httpResponse = (HttpServletResponse)response;   
		String requestURI = httpRequest.getRequestURI();   

		if(!isFreePage(requestURI)) { //如果是保护页面   
			if(!isValidSession(request)) { //如果Session无效   
				String loginPageURL = null;   
				try {   
					loginPageURL = httpRequest.getContextPath() + this.loginPage; 
					httpResponse.setHeader("User-Defined-Session-Status","timeout/reset");     
					httpResponse.encodeRedirectURL(loginPageURL);   
					httpResponse.sendRedirect(loginPageURL); //转发响应   
				} 
				catch(IOException ex) {   

				}   
			}   
		}   
	  
		if(!httpResponse.isCommitted()) { //如果响应未提交,交给过滤器链   
			try {   
				filterChain.doFilter(request, response);   
			} 
			catch(ServletException e) {   
				filterConfig.getServletContext().log(e.getMessage());   
			} 
			catch(IOException e) {   
				filterConfig.getServletContext().log(e.getMessage());   
			}   
		}   
	  
	}   
	  
	public void destroy() {   
	}   
	    
	public FilterConfig getFilterConfig() {   
		return this.filterConfig;   
	}   
	  
	public void setFilterConfig(FilterConfig filterConfig) {   
		this.filterConfig = filterConfig;   
	}   
}  